<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="issueArt">发表文章</el-button>
      </div>
      <!-- 弹出层 -->
        <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        :before-close="handleClose"
        fullscreen>
        <!-- 发布文章的对话框 -->
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
        <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
        <!-- 使用 v-model 进行双向的数据绑定 -->
        <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
        <!-- 用来显示封面的图片 -->
        <img v-if="cover_img" :src="cover_img" alt="" class="cover-img" ref="imgRef" />
        <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
        <br />
        <!-- 文件选择框，默认被隐藏 -->
        <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="changefileImg" />
        <!-- 选择封面的按钮 -->
        <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
            <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>
        </el-form>
        </el-dialog>
      <!-- 文章表格区域 -->
        <el-table
        border
      :data="artList"
      style="width: 100%">
      <el-table-column
        prop="title"
        label="文章标题"
        width="320">
        <template v-slot="{row}">
         <el-link type="primary" @click="showInfo(row)">{{row.title}}</el-link>
      </template>
      </el-table-column>
        <el-table-column
        prop="cate_name"
        label="文章标签"
        width="300">
      </el-table-column>
      <el-table-column
        prop="pub_date"
        label="发表时间"
        width="280">
        <template v-slot="scope">
            {{ formatDate(scope.row.pub_date) }}
        </template>
      </el-table-column>
        <el-table-column
        prop="state"
        label="状态"
        width="240">
      </el-table-column>
        <el-table-column
        label="操作">
        <template slot-scope="scope">
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.row)">删除</el-button>
      </template>
      </el-table-column>
    </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="q.pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="q.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 详情-->
    <el-dialog
  title="文章详情"
  :visible.sync="detailsVisible"
  width="80%"
  >
  <h1 class="title"> {{ details.title }}</h1>
  <div class="info">
      <span>作者： {{details.nickname || details.username}}</span>
      <span>发布时间：{{formatDate(details.pub_date)}}</span>
      <span>所属分类：{{details.cate_name}}</span>
      <span>状态：{{details.state}}</span>
      <!-- 分割线 -->
  <el-divider></el-divider>
  <!-- 文章封面 -->
  <img :src="'http://www.liulongbin.top:3008'+details.cover_img" alt="">
  <!-- 文章的详情 -->
  <div v-html="details.content" class="detail-box"></div>
  </div>
</el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入格式化时间
import dataFomate from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 控制弹出层
      dialogVisible: false,
      //   控制详情弹出
      detailsVisible: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      //   页数
      total: 0,
      cover_img: '',
      //   接收列表传入的数据
      artList: [],
      //   接收分类列表数据
      cateList: [],
      details: {},
      //   渲染表单需要绑定的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        // 文章内容
        content: '',
        // 文章封面
        cover_img: null,
        // 状态
        state: ''
      },
      //   表单项验证规则
      pubFormRules: {
        title: [
          { required: true, message: '请填写文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请选择文章封面', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //   格式化时间
    formatDate (date) {
      return dataFomate(date).format('YYYY-DD-MM HH:mm:ss')
    },
    //   点击发表文章弹出对话框
    issueArt () {
      this.dialogVisible = true
    },
    // 关闭的回调
    async handleClose (done) {
      const confirmresult = await this.$confirm('确认关闭吗，关闭后内容都将丢失哦？', '温馨提示', {
        type: 'warning'
      })
        .catch(err => err)
        // 取消关闭
      if (confirmresult === 'cancel') return
      // 关闭
      done()
    },
    // 渲染文章分类的每一项
    async getArtCates () {
      // 请求数据
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code !== 0) return
      this.cateList = res.data
    },
    changefileImg (e) {
      const files = e.target.files
      if (files.length === 0) {
        this.pubForm.cover_img = null
        this.cover_img = null
      } else {
        this.$refs.pubFormRef.clearValidate('cover_img')
        this.pubForm.cover_img = files[0]
        this.cover_img = URL.createObjectURL(files[0])
      }
    },
    // 发布文章
    pubArticle (state) {
      this.pubForm.state = state
      // 兜底校验
      this.$refs.pubFormRef.validate(async result => {
        if (!result) return
        // 创建formData对象
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        // 发起请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return
        // 关闭表单
        this.dialogVisible = false
        // 重置表单
        this.$refs.pubFormRef.resetFields()
        // 图片置空
        this.pubForm.cover_img = null
        this.cover_img = null
        this.pubForm.state = ''
        // 刷新列表项
        this.getArtList()
      })
    },
    // 渲染表格列表
    async getArtList () {
      // 发送请求
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code !== 0) return
      this.total = res.total
      this.artList = res.data
    },
    // 删除表单项
    async handleDelete (row) {
      console.log(row)
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { type: 'warning' }).catch(e => e)
      if (res === 'cancel') return
      //   发送删除请求
      this.$http.delete('/my/article/info', {
        params: { id: row.id }
      }).then(res => {
        if (res.data.code !== 0) return
        //   如果当前页只有一条了 就让它跳到前一页
        if (this.artList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }
        this.getArtList()
      })
    },
    // 重置过滤项
    resetFilter () {
      this.q.cate_id = ''
      this.q.state = ''
      // 重新加载页面
      this.getArtList()
    },
    // 分页大小变化
    handleSizeChange (e) {
      this.q.pagesize = e
      this.getArtList()
    },
    // 选择页码
    handleCurrentChange (e) {
      this.q.pagenum = e
      this.getArtList()
    },
    async showInfo (row) {
      this.detailsVisible = true
      //   根据id获取文章详情
      const { data: res } = await this.$http.get('/my/article/info', {
        params: { id: row.id }
      })
      if (res.code !== 0) return
      this.details = res.data
      console.log(this.details)
    }
  },
  created () {
    // 挂载文章分类项
    this.getArtCates()
    // 自动加载表格项数据
    this.getArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
.cover-img{
    width: 450px;
    height: 315px;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
